import 'dart:async';
import 'dart:io';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:fate_blind_box/theme/theme_color.dart';
import 'package:fate_blind_box/ui/login/personinformation/personinformation_two.dart';
import 'package:fate_blind_box/utils/common_widget.dart';
import 'package:fate_blind_box/utils/default/common_config.dart';
import 'package:fate_blind_box/utils/loading.dart';
import 'package:fate_blind_box/widget/icon_text.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:universal_html/html.dart' as html;
import '../../../network/Api.dart';
import '../../../utils/page.dart';
import '../../../utils/provider.dart';
import '../../../utils/snack_bar.dart';
import '../../../widget/date_picker/flutter_datetime_picker.dart';


class PersonInformationPage extends StatefulWidget {
  const PersonInformationPage({Key? key}) : super(key: key);

  @override
  State<PersonInformationPage> createState() => _PersonInformationPageWidget();
}

class _PersonInformationPageWidget extends State<PersonInformationPage> {
  late Size _screen;
  final _nickNameController = TextEditingController();
  int _gender = 2;
  final _birthdayController = TextEditingController();
  final _addressController = TextEditingController();
  final _pcaOriginalList = [];
  final _pcaList = [];
  String? _albumId = "";

  late String _avatarFilePath = "";

  bool isShowPermission = false;

  @override
  void initState() {
    super.initState();
    if(CommonConfig.isHuaWeiPermission){
      isOpenCameraPermission().then((value) {
        setState(() {
          isShowPermission = value;
        });
      });
    }

    _getPcaList();
  }

  _getPcaList() async {
    final Response<dynamic> res = await Api.getInstance().getPcaList();
    _pcaOriginalList.addAll(res.data);
    for (var i in res.data) {
      final item = <String, dynamic>{};
      final cities = [];
      for (var c in i['children']) {
        final area = [];
        final city = <String, dynamic>{};
        for (var a in c['children']) {
          area.add(a['name']);
        }
        city[c['name']] = area;
        cities.add(city);
      }
      item[i['name']] = cities;
      _pcaList.add(item);
    }
  }

  @override
  Widget build(BuildContext context) {
    _screen = MediaQuery.of(context).size;
    return Stack(
      children: [
        AppWidget.navTitleBar(
          titleWidget: Column(
            children: [
              const Text(
                '完善资料1/2',
                style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w500,
                    color: Color(0xFF2C2C2C)),
              ),
              Container(
                margin: const EdgeInsets.only(top: 4),
                child: Image.asset(
                  'images/person_progress_one1.png',
                  width: 88,
                  height: 4,
                ),
              ),
            ],
          ),
          bgColor: Colors.white,
          childWidget: Container(
            decoration: ShapeDecoration(
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(15)),
                color: Colors.white),
            child: SingleChildScrollView(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Container(
                    margin: const EdgeInsets.only(top: 40.0, left: 10),
                    child: Stack(children: [
                      GestureDetector(
                        child: _avatarFilePath.isNotEmpty
                            ? ClipRRect(
                                borderRadius: BorderRadius.circular(5),
                                child: Image(
                                  image: CachedNetworkImageProvider(
                                      Provider.fixAvatar(_avatarFilePath)),
                                  height: 86,
                                  width: 86,
                                ),
                              )
                            : Image.asset(
                                'images/ic_AvtarMe.png',
                                width: 86,
                                height: 86,
                              ),
                        onTap: () {
                          _selectPhoto(context, 'title', _screen.width);
                        },
                      ),
                      Container(
                        margin: const EdgeInsets.only(top: 55, left: 70),
                        child: Image.asset(
                          "images/my_xj.png",
                          width: 28,
                          height: 28,
                        ),
                      ),
                    ]),
                  ),

                  Container(
                    margin: const EdgeInsets.only(
                      top: 2,
                    ),
                    child: Image.asset(
                      'images/person_tishi.png',
                      width: 100,
                      height: 17,
                    ),
                  ),
                  //昵称
                  Container(
                    alignment: Alignment.topLeft,
                    margin: const EdgeInsets.fromLTRB(41, 51, 0, 0),
                    child: Text(
                      "昵称",
                      style:
                          TextStyle(fontSize: 16, color: ThemeColor.textColor),
                    ),
                  ),
                  Container(
                    margin: const EdgeInsets.fromLTRB(41, 10, 41, 0),
                    height: 45,
                    color: const Color(0xFFF6F8FA),
                    child: TextField(
                      controller: _nickNameController,
                      maxLength: 11,
                      // keyboardType: TextInputType.phone,
                      cursorColor: const Color(0xFFFB6D99),

                      style: const TextStyle(
                          fontSize: 12, color: Color(0xFF222222)),
                      decoration: InputDecoration(
                        hintText: "请输入昵称",
                        counterText: "",
                        border: InputBorder.none,
                        hintStyle: const TextStyle(color: Color(0xFF999999)),
                        fillColor: const Color(0xffF1F3FB),
                        filled: true,
                        enabledBorder: const OutlineInputBorder(
                          /*边角*/
                          borderRadius: BorderRadius.all(
                            Radius.circular(5), //边角为30
                          ),
                          borderSide: BorderSide(
                            color: Colors.white54, //边线颜色为黄色
                            width: 1, //边线宽度为2
                          ),
                        ),
                        focusedBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(5),
                          borderSide: const BorderSide(
                            color: Colors.white54, //边框颜色为绿色
                            width: 1, //宽度为5
                          ),
                        ),
                      ),
                      onChanged: (e) {
                        setState(() {});
                      },
                    ),
                  ),

                  //性别
                  const SizedBox(
                    height: 24,
                  ),
                  Container(
                    margin: const EdgeInsets.only(left: 41),
                    alignment: Alignment.topLeft,
                    child: const Text(
                      "性别",
                      style: TextStyle(fontSize: 16),
                    ),
                  ),

                  const SizedBox(
                    height: 8,
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      const SizedBox(
                        width: 41,
                      ),
                      Expanded(
                        flex: 1,
                        child: GestureDetector(
                          onTap: () {
                            setState(() {
                              _gender = 2;
                            });
                          },
                          child: Container(
                            alignment: Alignment.center,
                            height: 44,
                            decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(8),
                                border: _gender == 2
                                    ? Border.all(
                                        color: const Color(0xFFFF5998),
                                        width: 2,
                                      )
                                    : null,
                                color: Color(
                                    _gender == 2 ? 0xFFF5D8E3 : 0xFFF6F8FA)),
                            child: IconText(
                              "    女生",
                              icon: Image.asset(
                                "images/ic_avatar_def_girl.png",
                                width: 32,
                                height: 32,
                              ),
                            ),
                          ),
                        ),
                      ),
                      const SizedBox(
                        width: 13,
                      ),
                      Expanded(
                        flex: 1,
                        child: GestureDetector(
                          onTap: () {
                            setState(() {
                              _gender = 1;
                            });
                          },
                          child: Container(
                            alignment: Alignment.center,
                            width: (_screen.width - 42) / 2,
                            height: 44,
                            decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(8),
                                border: _gender == 1
                                    ? Border.all(
                                        color: const Color(0xFF59B8FF),
                                        width: 2,
                                      )
                                    : null,
                                color: Color(
                                    _gender == 1 ? 0xFFD8EAF5 : 0xFFF6F8FA)),
                            child: IconText(
                              "    男生",
                              icon: Image.asset(
                                "images/ic_avatar_def_boy.png",
                                width: 32,
                                height: 32,
                              ),
                            ),
                          ),
                        ),
                      ),
                      const SizedBox(
                        width: 41,
                      ),
                    ],
                  ),

                  Container(
                    alignment: Alignment.topLeft,
                    margin: const EdgeInsets.fromLTRB(41, 10, 0, 0),
                    child: const Text(
                      "性别提交后无法更改哦",
                      style: TextStyle(fontSize: 12, color: Color(0xFF7F69D9)),
                    ),
                  ),
                  const SizedBox(
                    height: 24,
                  ),

                  //生日
                  Container(
                    alignment: Alignment.topLeft,
                    margin: const EdgeInsets.only(left: 41),
                    child: Text(
                      "生日",
                      style:
                          TextStyle(fontSize: 16, color: ThemeColor.textColor),
                    ),
                  ),
                  Container(
                    margin: const EdgeInsets.fromLTRB(41, 10, 41, 10),
                    height: 45,
                    color: const Color(0xFFF6F8FA),
                    child: TextField(
                      controller: _birthdayController,
                      maxLength: 11,
                      keyboardType: TextInputType.phone,
                      cursorColor: const Color(0xFFFB6D99),
                      style: const TextStyle(
                          fontSize: 12, color: Color(0xFF222222)),
                      readOnly: true,
                      decoration: InputDecoration(
                        hintText: "请选择",
                        hintStyle: TextStyle(
                          fontSize: 12,
                          color: ThemeColor.textColorSecond,
                        ),
                        // suffixText: '请选择',
                        // suffixStyle: TextStyle(fontSize: 12, color: ThemeColor.textColorSecond),
                        counterText: "",
                        border: InputBorder.none,
                        // hintStyle: TextStyle(color: Color(0xFF999999)),
                        suffixIcon: Icon(
                          Icons.keyboard_arrow_right_rounded,
                          size: 24,
                          color: ThemeColor.textColorSecond,
                        ),

                        fillColor: const Color(0xffF1F3FB),
                        filled: true,
                        enabledBorder: const OutlineInputBorder(
                          /*边角*/
                          borderRadius: BorderRadius.all(
                            Radius.circular(5), //边角为30
                          ),
                          borderSide: BorderSide(
                            color: Colors.white54, //边线颜色为黄色
                            width: 1, //边线宽度为2
                          ),
                        ),
                        focusedBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(5),
                          borderSide: const BorderSide(
                            color: Colors.white54, //边框颜色为绿色
                            width: 1, //宽度为5
                          ),
                        ),
                      ),
                      onTap: () async {
                        DatePicker.showDatePicker(context,
                            showTitleActions: true,
                            minTime: DateTime(1950, 1, 1),
                            maxTime: DateTime(2005, 12, 31),
                            onChanged: (date) {}, onConfirm: (date) {
                          // '$date'

                          _birthdayController.text =
                              date.toString().split(' ')[0];
                        }, currentTime: DateTime.now(), locale: LocaleType.zh);
                      },
                      onChanged: (e) {
                        setState(() {
                          // _loginBtnSelector = _pwdController.text.length >= 6 && e.length >= 11 ? _loginBtnEnable : _loginBtnUnable;
                        });
                      },
                    ),
                  ),
                  GestureDetector(
                    onTap: () {
                      _submit();
                    },
                    child: Container(
                      height: 45,
                      margin: const EdgeInsets.fromLTRB(73, 80, 76, 0),
                      decoration: BoxDecoration(
                          // gradient: const LinearGradient(
                          //     begin: Alignment.topCenter,
                          //     end: Alignment.bottomCenter,
                          //     colors: [Color(0xFFB1A3E4), Color(0xFF7278E5)]
                          // ),
                          color: const Color(0xFF7F69D9),
                          borderRadius: BorderRadius.circular(22.5)),
                      alignment: Alignment.center,
                      child: const Text(
                        "下一步",
                        style: TextStyle(color: Colors.white, fontSize: 18),
                      ),
                    ),
                  ),
                  const SizedBox(
                    height: 20,
                  ),
                ],
              ),
            ),
          ),
        ),
        Positioned(
          child: Visibility(
            visible: isShowPermission,
            child: GestureDetector(
              onTap: () {
                setState(() {
                  isShowPermission = false;
                });
              },
              child: Container(
                width: 1.sw,
                height: 1.sh,
                color: const Color.fromRGBO(0, 0, 0, 0.2),
                child: Column(
                  children: [
                    Container(
                      padding: EdgeInsets.only(
                          left: 30, top: ScreenUtil().statusBarHeight),
                      width: 1.sw,
                      height: 90,
                      color: Colors.white,
                      child: const Text(
                        '相机、相册权限说明\n获取相机权限和相册权限，用于上传编辑头像',
                        style: TextStyle(fontSize: 16),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      ],
    );

    ;
  }

  bool _verify(bool sendCode) {
    // if (_avatarFilePath.toString().isEmpty) {
    //   toast("请上传头像");
    //   return false;
    // }

    if (_nickNameController.text.isEmpty) {
      toast("请输入昵称");
      return false;
    }

    if (_birthdayController.text.isEmpty) {
      toast("请选择生日");
      return false;
    }

    return true;
  }

  Future<void> _selectPhoto(context, String title, double width) async {
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return SizedBox(
            height: 220.0,
            child: Container(
                alignment: Alignment.center,
                child: Column(
                  children: [
                    GestureDetector(
                        onTap: () {
                          getAlbumImg('拍照');
                        },
                        child: Container(
                          alignment: Alignment.center,
                          width: width,
                          height: 55,
                          color: Colors.white,
                          child: const Text('拍照'),
                        )),
                    Divider(
                      color: ThemeColor.sendMsgColor,
                      height: 1,
                    ),
                    GestureDetector(
                        onTap: () {
                          getAlbumImg('相册');
                        },
                        child: Container(
                          alignment: Alignment.center,
                          width: width,
                          height: 60,
                          color: Colors.white,
                          child: const Text('从手机相册选择'),
                        )),
                    Divider(
                      color: ThemeColor.sendMsgColor,
                      thickness: 7,
                      height: 1,
                    ),
                    GestureDetector(
                        onTap: () {
                          Navigator.pop(context);
                        },
                        child: Container(
                          alignment: Alignment.center,
                          width: width,
                          height: 55,
                          child: const Text('取消'),
                        ))
                  ],
                )));
      },
    );
  }

  _submit() {
    if (!_verify(false)) {
      return;
    }

    print(
        '${Provider.memberId}\n${_nickNameController.text}\n$_gender\n${_birthdayController.text}\n$_avatarFilePath');
    loading(() async {
      final res = await Api.getInstance().perfectInformationAvator(
        Provider.memberId,
        _nickNameController.text,
        _gender,
        _birthdayController.text,
        _avatarFilePath,
      );
      if (res['code'] == 0) {
        Navigate.toPage(const PersonInformationTwoPage());
      } else {
        toast(res['msg']);
      }
    });
  }

  void getAlbumImg(String type) {
    Navigator.pop(context);
    if (kIsWeb) {
      loading(() async {
        final uploadInputElement = html.FileUploadInputElement();
        uploadInputElement.multiple = false;
        uploadInputElement.draggable = true;
        uploadInputElement.click();
        uploadInputElement.onChange.listen((event) {
          final file = uploadInputElement.files?.first;

          if (file != null) {
            final uploadInputElement = html.FileUploadInputElement();
            uploadInputElement.multiple = false;
            uploadInputElement.draggable = true;
            uploadInputElement.click();
            uploadInputElement.onChange.listen((event) {
              final file = uploadInputElement.files?.first;
              if (file != null) {
                loading(() async {
                  final formData = html.FormData();
                  formData.appendBlob("avatarfile", file.slice(), file.name);
                  formData.append("memberId", Provider.memberId);
                  Api.getInstance().uploadAvatarFromHtml(formData, (e) {
                    if (e['code'] == 0) {
                      setState(() {
                        _avatarFilePath = e['data']['url'];
                      });
                    } else {
                      ThemeSnackBar.show(context, e['msg']);
                    }
                  });
                });
              }
            });
          }
        });
      });
    } else {
      loading(() async {
        final picker = ImagePicker();

        ImageSource source;
        if (type == '拍照') {
          source = ImageSource.camera;
        } else {
          source = ImageSource.gallery;
        }
        final pickerFile =
            await picker.pickImage(source: source, imageQuality: 50);
        if (pickerFile != null) {
          CroppedFile? croppedImage = await ImageCropper().cropImage(
              sourcePath: pickerFile.path,
              //图片资源
              maxHeight: 500,
              maxWidth: 500,
              aspectRatio: const CropAspectRatio(ratioX: 1, ratioY: 1),
              //裁剪框比例
              uiSettings: [
                AndroidUiSettings(
                    toolbarTitle: '裁剪', lockAspectRatio: true //锁定图片纵横比
                    ),
                IOSUiSettings(
                    title: '裁剪',
                    resetButtonHidden: true,
                    //不显示重置按钮
                    aspectRatioLockEnabled: true,
                    //锁定图片纵横比
                    aspectRatioPickerButtonHidden: true,
                    //隐藏切换纵横比按钮
                    doneButtonTitle: "完成",
                    //confirm按钮文字
                    cancelButtonTitle: "取消" //cancel按钮文字
                    )
              ]); //根据XFile对象的路径获得图片进行裁剪
          //裁剪完成

          if (croppedImage != null) {
            //裁剪后图片的路径
            String filepath = croppedImage.path;
            final res = await Api.getInstance()
                .uploadAvatar(Provider.memberId, filepath); //pickerFile.path
            if (res['code'] == 0) {
              final data = res['data'];
              setState(() {
                _avatarFilePath = data['url'];
                ThemeSnackBar.show(context, res['msg']);
              });
            } else {
              ThemeSnackBar.show(context, res['msg']);
            }
            print("filepath-----$filepath");
          }
        }
      });
    }
  }

//相机权限
  Future<bool> isOpenCameraPermission() async {
    var status = await Permission.camera.status;
    if (status.isGranted) {
      return false;
    }
    return true;
  }
}
